package net.asfun.jvalog.vo;

import java.util.ArrayList;
import java.util.List;

import net.asfun.jvalog.common.InteractException;
import net.asfun.jvalog.common.JdoerFactory;
import net.asfun.jvalog.entity.Relation;
import net.asfun.jvalog.entity.Sort;
import net.asfun.jvalog.resource.MeterDao;
import net.asfun.jvalog.util.Bridge;

public class Category{
	
	private Sort sort; 
	
	private List<Relation> pos;
	
	public Category(Sort sort) {
		if ( sort == null) {
			throw new InteractException("Category not found");
		}
		this.sort = sort;
	}
	
	public int getOrder() {
		return sort.getOrder();
	}
	
	public String getName() {
		return sort.getName();
	}
	
	public String getSlogan() {
		return sort.getSlogan();
	}
	
	public Long getId() {
		return sort.getKey().getId();
	}
	
	public int getPostCount() {
		return MeterDao.getCount(sort.getKey());
	}
	
	private void setPosts() {
		if ( null == pos ) {
			pos = Bridge.getRelationsByRight(sort.getKey(), Bridge.POST_CATEGORY);
		}
	}
	
	public List<Post> listPublishedPosts(Pager pager) {
		pager.setTotal(getPostCount());
		List<Post> list = new ArrayList<Post>();
		int j=0;
		setPosts();
		for(int i=pos.size(); i>0; ) {
			Post post = Post.load(pos.get(--i).getLeft().getId());
			if ( post != null && post.isPublished() ) {
				//paging
				if ( j >= pager.getStart() && 
						j < pager.getEnd() ) {
					list.add(post);
				}
				j++;
			}
		}
		if ( list.isEmpty() && pager.getIndex() > 1) {
			throw new InteractException("Category pager no record");
		}
		return list;
	}

	public String getLink() {
		return Site.getInstance().getUrl() + "category/" + sort.getSlogan();
	}

	protected static Category load(long id) {
		return new Category(JdoerFactory.jdoSort.load(id));
	}

}
